package cn.stylefeng.guns.modular.business.frequency.ledgerrecords.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.PageUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.business.app.mapper.BalancePaymentMapper;
import cn.stylefeng.guns.modular.business.app.pojo.BalancePayment;
import cn.stylefeng.guns.modular.business.frequency.ledgerrecords.controller.dto.LedgerRecordsDTO;
import cn.stylefeng.guns.modular.business.frequency.ledgerrecords.controller.vo.PageVO;
import cn.stylefeng.guns.modular.business.frequency.ledgerrecords.service.LedgerRecordsService;
import cn.stylefeng.guns.sys.modular.user.entity.SysTenant;
import cn.stylefeng.guns.sys.modular.user.mapper.SysTenantMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.stylefeng.guns.core.pojo.page.PageResult.RAINBOW_NUM;

@Service
public class LedgerRecordsServiceImpl implements LedgerRecordsService {

    @Autowired
    private BalancePaymentMapper balancePaymentMapper;

    @Autowired
    private SysTenantMapper sysTenantMapper;

    /**
     * 条件分页查询分账记录
     */
    @Override
    public PageResult<LedgerRecordsDTO> page(PageVO pageVO) {
        //创建PageResult对象
        PageResult<LedgerRecordsDTO> pageResult = new PageResult<>();

        LambdaQueryWrapper<BalancePayment> wrapper = new LambdaQueryWrapper<>();
        if (!LoginContextHolder.me().isTenantUser()) {
            wrapper.eq(BalancePayment::getTenantId, LoginContextHolder.me().getTenantId());
        }
        // 当传递的条件不为空时需要拼接
        if (Objects.nonNull(pageVO)) {
            //拼接条件
            if (StringUtils.isNotEmpty(pageVO.getBeginTime()) && StringUtils.isNotEmpty(pageVO.getEndTime())) {
                wrapper.between(BalancePayment::getCreateTime, stringToDate(pageVO.getBeginTime()), stringToDate(pageVO.getEndTime()));
            }
            if (Objects.nonNull(pageVO.getTenantName())) {
                //先根据租户名模糊查询租户id
                List<SysTenant> sysTenantList = sysTenantMapper.selectList(new LambdaQueryWrapper<SysTenant>()
                        .like(SysTenant::getName, pageVO.getTenantName()));
                List<Long> list = sysTenantList.stream().map(SysTenant::getId).collect(Collectors.toList());
                wrapper.in(CollectionUtil.isNotEmpty(list), BalancePayment::getTenantId, list);
            }
        }
        wrapper.orderByDesc(BalancePayment::getCreateTime);
        Page<BalancePayment> page = balancePaymentMapper.selectPage(PageFactory.defaultPage(), wrapper);

        //将page数据转换到pageResult对象中
        handler(page, pageResult);
        //返回结果
        return pageResult;
    }

    private Date stringToDate(String time) {
        Date date = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将page数据转换到pageResult对象中
     */
    private void handler(Page<BalancePayment> page, PageResult<LedgerRecordsDTO> pageResult) {
        //将查询的数据BalancePayment转换为LedgerRecordsDTO
        List<BalancePayment> balancePaymentList = page.getRecords();

        //校验后遍历
        if (Objects.nonNull(balancePaymentList) && balancePaymentList.size() > 0) {
            List<LedgerRecordsDTO> ledgerRecordsDTOList = balancePaymentList.stream().map(s -> {
                //创建LedgerRecordsDTO对象
                LedgerRecordsDTO ledgerRecordsDTO = new LedgerRecordsDTO();

                //分账金额
                ledgerRecordsDTO.setDividendAmount(s.getDividendAmount());

                //分账时间
                ledgerRecordsDTO.setTime(s.getCreateTime());

                //根据租户id查询租户名称
                SysTenant sysTenant = sysTenantMapper.selectOne(new LambdaQueryWrapper<SysTenant>()
                        .eq(SysTenant::getId, s.getTenantId()));
                ledgerRecordsDTO.setTenantName(sysTenant.getName());

                return ledgerRecordsDTO;
            }).collect(Collectors.toList());

            pageResult.setRows(ledgerRecordsDTOList);
        }

        //其他属性
        pageResult.setTotalRows(Convert.toInt(page.getTotal()));
        pageResult.setPageNo(Convert.toInt(page.getCurrent()));
        pageResult.setPageSize(Convert.toInt(page.getSize()));
        pageResult.setTotalPage(PageUtil.totalPage(Convert.toInt(page.getTotal()),
                Convert.toInt(page.getSize())));
        pageResult.setRainbow(PageUtil.rainbow(Convert.toInt(page.getCurrent()),
                Convert.toInt(pageResult.getTotalPage()), RAINBOW_NUM));
    }
}
